import { cloneElement, forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { Form, Modal } from 'antd';

/**
 * 表单弹窗组件
 *
 * @param {FormInstance} form 表单实例
 * @param {string} title 弹窗标题
 * @param {string} name 表单名称
 * @param {ReactNode} trigger 触发弹窗的控件
 * @param {ReactNode} formItems 表单项
 * @param {Function} onFinish 表单提交回调
 * @param {string} layout 表单布局
 * @param {width} width 弹窗宽度
 */
export default forwardRef(function FormModal(props, ref) {
  const {
    title,
    name,
    trigger,
    formItems,
    onFinish,
    layout = 'vertical',
    width = 300,
    form
  } = props;

  useImperativeHandle(ref, () => ({
    open: () => setOpen(true),
    close: () => setOpen(false)
  }));

  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!open && form) {
      form?.resetFields();
    }
  }, [open, form]);

  // 点击触发控件
  const triggerWithOnClick = cloneElement(trigger ?? <></>, {
    onClick: () => setOpen(true)
  });

  // 提交表单
  const handleSubmit = async (data) => {
    setLoading(true);
    onFinish && (await onFinish(data));
    setLoading(false);
  };

  return (
    <>
      {triggerWithOnClick}
      <Modal
        title={title}
        open={open}
        onOk={form?.submit}
        onCancel={() => setOpen(false)}
        width={width}
        confirmLoading={loading}
      >
        <Form form={form} name={name} layout={layout} onFinish={handleSubmit}>
          {formItems}
        </Form>
      </Modal>
    </>
  );
});
